#!/usr/bin/env bash

# drobban@sdfeu
source '../say.sh'

nick="$1"
chan="$2"
arg="$3"

get_val(){
    #arg 1 key.
    #arg 2 type (s = string, n = num)
    #arg 3 string to fetch key from
    #arg 4 reference to var
    case ${2} in
        s)
            t=`grep -Po "\""${1}"\":\"\K(\w|\s)*" <<< ${!3}`
            printf -v $4 '%s' "$t"
            ;;
        n)
            t=`grep -Po "\""${1}"\":\K(\-|\.|[0-9]+)*" <<< ${!3}`
            printf -v $4 '%s' "$t"
            ;;
    esac
}

if [[ "$arg" =~ [a-z]+\,[a-z]+$ ]]; then
    site="${arg^^}"
    url="api.openweathermap.org/data/2.5/weather?q=$site&units=metric&appid=ef4b86aedd2b2645317ac3b7a22e56f4"
    report="$(curl -X GET "$url")"
    if [[ -z "$report" ]]; then
        msg='The requested location is not in the database or the server is down.'
    else
        location=''
        get_val "name" "s" report location
        temp=''
        get_val "temp" "n" report temp
        humid=''
        get_val "humidity" "n" report humid
        wind=''
        get_val "speed" "n" report wind
        direction=''
        get_val "deg" "n" report direction
        description=''
        get_val "description" "s" report description
        description=`tr -d "\n" <<< $description`

        printf -v msg \
               '%s\n%s\n%s\n%s\n%s'\
               "OW: Location: $location"\
               "OW: Temperature: $temp C"\
               "OW: Humidity: $humid%"\
               "OW: Wind speed/direction: $wind meter/second $direction deg"\
               "OW: Description: $description"
        readarray -t msg <<< "$msg"
    fi
else
    chan="$nick"
    msg=(
        'The command !oweather prints observations reported to http://openweathermap.org'
        'First argument: location'
        'location format: {city name},{country code}'
        'location example: berlin,de'
        'Use ISO 3166-2 country codes https://en.wikipedia.org/wiki/ISO_3166'
    )
fi

say "$chan" "${msg[@]}"

